// pages/collectiionAndFocus/collectiionAndFocus.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hiddenLoading: false,
    noCollection: false,
    noFocus: false,
    collections: [],
    startX: 0, //开始坐标
    startY: 0,
    domain: app.api.domain,
    windowWidth: '',
    windowHeight: '',
    scrollHeight: '',
    lock: false, //长按锁
    shops: [],
    p: 1, //收藏分页码
    page: 1, // 店铺分页码
    collectEnd: false,
    storeEnd: false,
    type: 0,
    toggle: true,
    partData: {
      imgUrls: '',
      name: '',
      inventory: 0,
      price: '',
      goods_id: '',
      detail: false
    },
  },

  toSimilar(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/detail/pages/search/search?id=${id}&where=similar`,
    })
  },

  // 跳转详情
  toGoodsDetail(e) {
    const that = this;
    let id = e.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: `/page/detail/pages/details/details?id=${id}`,
    })
  },

  // 添加到购物车
  addToCart(e) {
    const that = this;
    let goodsid = e.currentTarget.dataset.goodsid;
    let token = app.globalData.token;
    let valid = e.currentTarget.dataset.valid;
    if (valid == 0) {
      app.showInfo('此商品不存在或者已下架');
      return
    }
    let json = {
      token,
      goods_num: 1,
      goods_id: goodsid,
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.addCart, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        // 添加成功
        wx.showToast({
          title: '已添加到购物车',
          icon: 'success',
          duration: 1000
        })
        app.getCartCount();
      } else {
        throw res.msg;
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })

  },


  switch2collection() {
    const that = this;
    that.setData({
      // toggle: true,
      collections: [],
      hiddenLoading: false,
      page: 1,
      storeEnd: false
    })
    wx.setNavigationBarTitle({
      title: '商品收藏',
    })
    that.getCollectionList();
  },


  switch2focus() {
    const that = this;
    that.setData({
      // toggle: false,
      shops: [],
      hiddenLoading: false,
      p: 1,
      collectEnd: false
    })
    wx.setNavigationBarTitle({
      title: '店铺关注',
    })
    that.getStoreList();
  },

  toStoreDetail(e) {
    const that = this;
    let id = e.currentTarget.dataset.storeid;
    wx.navigateTo({
      url: `/page/detail/pages/store/store?id=${id}`,
    })
  },

  touchend(e) {
    if (this.data.lock) {
      setTimeout(() => {
        this.setData({
          lock: false
        });
      }, 100);
    }
  },

  // 取消收藏
  delCollection(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    let json = {
      token: app.globalData.token,
      goods_id: e.currentTarget.dataset.goodsid
    }
    let jsonData = app.utils.getSignData(json);
    wx.showModal({
      title: '',
      content: '是否取消收藏该商品',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(res) {
        if (res.confirm) {
          that.setData({
            hiddenLoading: false
          })
          app.utils.post(app.api.reqUrls.delCollection, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            if (res.status == 1) {
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 1000
              })
              that.data.collections.splice(index, 1);
              if (!that.data.collections.length) {
                that.setData({
                  noCollection: true
                })
              }
              that.setData({
                collections: that.data.collections
              })
              app.getInfo(app.globalData.token)
            } else {
              throw res.msg;
            }
          }).catch(err => {
            app.showInfo(err.toString());
          })
        } else {
          console.log('取消删除')
        }
      }
    })
  },

  // 取消关注
  delete(e) {
    const that = this;
    console.log(e)
    that.setData({
      lock: true // 确认触发长按
    })
    let index = e.currentTarget.dataset.index;
    let json = {
      token: app.globalData.token,
      store_id: e.currentTarget.dataset.storeid
    }
    let jsonData = app.utils.getSignData(json);
    wx.showModal({
      title: '',
      content: '是否取消关注该店铺',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(res) {
        if (res.confirm) {
          that.setData({
            hiddenLoading: false
          })
          app.utils.post(app.api.reqUrls.delStore, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            if (res.status == 1) {
              let shops = that.data.shops;
              shops.splice(index, 1);
              if (!shops.length) {
                that.setData({
                  noFocus: true
                })
              }
              that.setData({
                shops
              })
              app.getInfo(app.globalData.token)
            } else {
              throw res.msg;
            }
          }).catch(err => {
            app.showInfo(err.toString());
          })
        } else {
          console.log('取消删除')
        }
      }
    })
  },


  getCollectionList() {
    const that = this;
    let json = {
      token: app.globalData.token,
      p: that.data.p
    }
    let jsonData = app.utils.getSignData(json);

    app.utils.post(app.api.reqUrls.getCollection, jsonData).then(res => {
      // 取消加载动画
      that.setData({
        hiddenLoading: true
      })
      console.log(res)
      if (res.status == 1) {
        if (!res.result.length) {
          that.setData({
            noCollection: true
          })
        } else {
          app.getImg(res.result);
          that.setData({
            collections: res.result
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      if (err != undefined) {
        app.showInfo(err.toString())
      } else {
        console.log('服务器错误')
      }
    })
  },

  getMoreCollectionList() {
    const that = this;
    if (that.data.collectEnd) {
      return
    }
    let json = {
      token: app.globalData.token,
      p: that.data.p + 1
    }

    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.getCollection, app.utils.getSignData(json)).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (res.result != '') {
          app.getImg(res.result);
          that.setData({
            p: that.data.p + 1,
            collections: [...that.data.collections, ...res.result]
          })
        } else {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 1000
          })
          that.setData({
            collectEnd: true
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      if (err != undefined) {
        app.showInfo(err.toString())
      } else {
        console.log('服务器错误')
      }
    })
  },

  getStoreList() {
    const that = this;
    let json = {
      token: app.globalData.token,
    }
    let jsonData = app.utils.getSignData(json);
    app.utils.post(app.api.reqUrls.getStore, jsonData).then(res => {
      // 取消加载动画
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (!res.result.length) {
          that.setData({
            noFocus: true
          })
        } else {
          that.setData({
            shops: res.result
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      if (err != undefined) {
        app.showInfo(err.toString())
      } else {
        console.log('服务器错误')
      }
    })
  },

  getMoreStoreList() {
    const that = this;
    let json = {
      token: app.globalData.token,
      page: that.data.page + 1
    }
    let jsonData = app.utils.getSignData(json);
    app.utils.post(app.api.reqUrls.getStore, jsonData).then(res => {
      // 取消加载动画
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (res.result != '') {
          that.setData({
            page: that.data.page + 1,
            shops: [...that.data.shops, ...res.result]
          })
        } else {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 1000
          })
          that.setData({
            storeEnd: true
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      if (err != undefined) {
        app.showInfo(err.toString())
      } else {
        console.log('服务器错误')
      }
    })
  },

  getMore(e) {
    const that = this;
    if (that.data.toggle) {
      that.getMoreCollectionList();
    } else {
      that.getMoreStoreList();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    if (options.tab == 'collection') {
      // that.setData({
      //   toggle: true
      // })
      wx.setNavigationBarTitle({
        title: '商品收藏',
      })
      that.getCollectionList();
    }
    if (options.tab == 'focus') {
      // that.setData({
      //   toggle: false
      // })
      wx.setNavigationBarTitle({
        title: '店铺关注',
      })
      that.getStoreList();
    }



    try {
      const res = wx.getSystemInfoSync()
      that.setData({
        windowHeight: res.windowHeight,
        windowWidth: res.windowWidth,
        scrollHeight: res.windowHeight - 80 / 750 * res.windowWidth
      })
    } catch (e) {
      console.log(e);
    }
    // 判断是否渠道会员，type == 1是渠道会员
    if (app.globalData.userInfo) {
      that.setData({
        type: app.globalData.userInfo.type
      })
    }

  },
  // 点击添加购物车
  addShowCart(e) {
    const that = this;
    let goods = e.currentTarget.dataset.goods
    that.setData({
      toggle: false,
      'partData.imgUrls': goods.img,
      'partData.name': goods.goods_name,
      'partData.inventory': goods.store_count,
      'partData.price': goods.shop_price,
      'partData.goods_id': goods.goods_id,
    })
  },
  // 添加到购物车
  addToCart(e) {

    app.checkUserInfoAuthorizationCart().then(() => {
      const that = this;
      let token = app.globalData.token;
      let json = {
        token,
        goods_num: e.detail,
        goods_id: that.data.partData.goods_id,
      }
      let jsonData = app.utils.getSignData(json);
      app.utils.post(app.api.reqUrls.addCart, jsonData).then(res => {
        if (res.status == 1) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 2000
          })
          app.getCartCount();
          app.cartCountCallback = (res) => {
            that.setData({
              cartCount: res
            })
          }
        } else {
          throw res.msg
        }
      }).catch(err => {
        app.showInfo(err.toString())
      })

    })
  },
  onShow() {
    //数据统计
    // if (this.data.toggle){
    //   app.statistics("page/detail/pages/collectionAndFocus/collectionAndFocus", "商品收藏")
    // }else{
    //   app.statistics("page/detail/pages/collectionAndFocus/collectionAndFocus", "店铺关注")
    // }
  },
  /**
   * 手指触摸动作开始 记录起点X坐标
   */
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.collections.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      collections: this.data.collections
    })
  },
  /**
   * 滑动事件处理
   */
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });

    this.data.collections.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })

    //更新数据
    that.setData({
      collections: that.data.collections
    })
  },
  /**
   * 计算滑动角度
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

})